package com.example.annotations.handler;


import com.example.annotations.Length;
import com.example.annotations.NotNull;
import com.example.annotations.Phone;

import java.lang.annotation.Annotation;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 验证处理器
 * @Author: chen
 * @CreateTime: 2022-08-16
 * @Version: 1.0
 */
public class VerifyHandler {

    private static final Pattern CHINA_PATTERN = Pattern.compile("^((13[0-9])|(14[0,1,4-9])|(15[0-3,5-9])|(16[2,5,6,7])|(17[0-8])|(18[0-9])|(19[0-3,5-9]))\\d{8}$");

    public static String verify(Annotation annotation,Object data) {
        if (annotation.annotationType() == NotNull.class) {
            return notNullBack(annotation, data);
        }else if (annotation.annotationType() == Length.class) {
            return lengthBack(annotation,data);
        }else if (annotation.annotationType() == Phone.class){
            return phoneBack(annotation,data);
        }
        return "未找到匹配器";
    }

    // 这里返回的是不合法消息,空则合法
    public static String notNullBack(Annotation annotation, Object data) {
        NotNull notNull = (NotNull) annotation;
        if (data == null || "".equals(data.toString().trim()))  {
            return notNull.value();
        }
        return null;
    }

    public static String lengthBack(Annotation annotation, Object data) {
        Length length = (Length) annotation;
        if (data == null || length.length() > data.toString().trim().length())  {
            return length.value();
        }
        return null;
    }

    public static String phoneBack(Annotation annotation, Object data) {
        Matcher m = CHINA_PATTERN.matcher(Objects.toString(data));
        Phone phone = (Phone) annotation;
        if (!m.matches())  {
            return phone.value();
        }
        return null;
    }

}
